
import { Table, Button, Space, Modal, Form, Input, DatePicker, message } from 'antd';
import moment from 'moment'; // 日期处理库
import { getListApi } from '../../api/list';
import { useEffect, useState } from 'react';
import { updateListApi, deleteListApi } from '../../api/list';

const WarrantyTable = () => {
  const [dataSource, setDataSource] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  // 添加删除确认对话框状态
  const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
  const [deleteId, setDeleteId] = useState(null);

  // 获取数据
  useEffect(() => {
    const listApi = async () => {
      const res = await getListApi()
      if (res.data.status === 0) {
        setDataSource(res.data.data)
      } else {
        message.error(res.data.message)
      }
    }
    listApi()
  }, [])

  // 列定义
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '购买日期',
      dataIndex: 'startTime',
      key: 'startTime',
      render: (date) => moment(date).format('YYYY-MM-DD')
    },
    {
      title: '保修到期时间',
      dataIndex: 'endTime',
      key: 'endTime',
      render: (date) => moment(date).format('YYYY-MM-DD')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            onClick={() => handleEdit(record)}
          >
            修改
          </Button>
          <Button 
            danger 
            onClick={() => showDeleteConfirm(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 显示删除确认对话框
  const showDeleteConfirm = (id) => {
    setDeleteId(id);
    setIsDeleteModalVisible(true);
  };

  // 确认删除
  const confirmDelete = async () => {
    try {
      await deleteListApi({ id: deleteId });
      setDataSource(dataSource.filter(item => item.id !== deleteId));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
      console.error('删除失败:', error);
    } finally {
      setIsDeleteModalVisible(false);
    }
  };

  // 取消删除
  const cancelDelete = () => {
    setIsDeleteModalVisible(false);
  };

  // 原有的删除处理函数（保留但不再直接调用）
  const handleDelete = async(id) => {
    setDataSource(dataSource.filter(item => item.id !== id));
    await deleteListApi({id})
    message.success('删除成功');
  };

  // 修改处理函数
  const handleEdit = (record) => {
    setCurrentRecord(record);
    setIsModalVisible(true);
    
    // 设置表单初始值
    form.setFieldsValue({
      name: record.name,
      startTime: moment(record.startTime),
      endTime: moment(record.endTime)
    });
  };

  // 计算默认的保修到期时间（购买日期后一年）
  const handleStartTimeChange = (date) => {
    if (date) {
      const endTime = moment(date).add(1, 'year');
      form.setFieldsValue({ endTime });
    } else {
      form.setFieldsValue({ endTime: null });
    }
  };

  // 提交表单
  const handleFormSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      
      // 格式化日期为 YYYY-MM-DD 格式
      const formattedValues = {
        ...values,
        id: currentRecord.id, // 保留原记录ID
        startTime: moment(values.startTime).format('YYYY-MM-DD'),
        endTime: moment(values.endTime).format('YYYY-MM-DD')
      };
      
      console.log('修改的数据:', formattedValues);
      await updateListApi(formattedValues)
      const newDataSource = dataSource.map(item => {
        if (item.id === currentRecord.id) {
          return { ...item, ...formattedValues };
        }
        return item;
      });
      
      setDataSource(newDataSource);
      message.success('修改成功');
      setIsModalVisible(false);
    } catch (error) {
      console.error('表单验证失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 关闭弹窗
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  return (
    <div style={{ padding: 20, backgroundColor: 'white' }}>
      <Table 
        columns={columns}
        dataSource={dataSource}
        pagination={false}
        variant
        rowKey={record => record.id}
      />

      {/* 编辑弹窗 */}
      <Modal
        title="修改保修记录"
        open={isModalVisible}
        onOk={handleFormSubmit}
        onCancel={handleCancel}
        confirmLoading={loading}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          name="editWarrantyForm"
          size="large"
        >
          <Form.Item
            name="name"
            label="产品名称"
            rules={[
              { required: true, message: '请输入产品名称' },
              { max: 50, message: '名称不能超过50个字符' }
            ]}
          >
            <Input placeholder="请输入产品名称" />
          </Form.Item>

          <Form.Item
            name="startTime"
            label="购买日期"
            rules={[{ required: true, message: '请选择购买日期' }]}
          >
            <DatePicker 
              style={{ width: '100%' }} 
              placeholder="选择购买日期"
              onChange={handleStartTimeChange}
            />
          </Form.Item>

          <Form.Item
            name="endTime"
            label="保修到期时间"
            rules={[{ required: true, message: '请选择保修到期时间' }]}
          >
            <DatePicker 
              style={{ width: '100%' }} 
              placeholder="选择保修到期时间"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 删除确认弹窗 */}
      <Modal
        title="确认删除"
        open={isDeleteModalVisible}
        onOk={confirmDelete}
        onCancel={cancelDelete}
        okText="确认"
        cancelText="取消"
      >
        <p>确定要删除这条保修记录吗？此操作不可恢复。</p>
      </Modal>
    </div>
  );
};

export default WarrantyTable;